package com.example.ecas.service.impl;

import com.example.ecas.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String adminEmail;

    @Override
    public String toUserEmailWithCode(String email) throws MessagingException, javax.mail.MessagingException {
        // 获取邮箱验证码
        String authCode = (Math.random()+"").substring(3,9);
        // 创建空的邮件信息对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 获取信息编辑的辅助对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        // 通过辅助对象设置信息内容
        helper.setFrom(adminEmail);
        helper.setTo(email);
        helper.setSubject("[欢迎使用]电子病历解析用户邮件服务");
        helper.setText("您好，您的验证码是：【"+authCode+"】 用于电子病历解析系统身份验证，5分钟内有效，请勿泄露和转发。如非本人操作，请忽略此邮件。" );
        // 发送信息
        mailSender.send(mimeMessage);
        return authCode;
    }
}
